package com.young.monitor.worker;

import com.young.common.util.DateUtil;
import com.young.monitor.configuration.MonitorServerConfiguration;
import com.young.monitor.service.IApiTraceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * 历史日志清理任务
 */
@Component
@EnableScheduling
public class HistoryTraceClearWorker {
    private static final Logger logger = LoggerFactory.getLogger(HistoryTraceClearWorker.class);

    @Autowired
    private IApiTraceService apiTraceService;

    @Autowired
    private MonitorServerConfiguration monitorServerConfiguration;

    //每天晚上0点10分
    @Scheduled(cron = "0 10 0 * * ?")
    private void exec() {
        try {
            if (monitorServerConfiguration.getStorageDays() == null || monitorServerConfiguration.getStorageDays() < 1) {
                logger.info("[历史日志清理任务] 链路数据存储天数配置(young.monitor.server.storage-days)={},本次不清理历史数据", monitorServerConfiguration.getStorageDays());
                return;
            }
            Date date = DateUtil.afterNDay(new Date(), - monitorServerConfiguration.getStorageDays());
            int num = apiTraceService.deleteDataBefore(date);
            logger.info("[历史日志清理任务] 本次清理完成,日期={},删除数据量={}", DateUtil.dateFormat(date), num);
        } catch (Throwable t) {
            logger.error("[历史日志清理任务] 发生异常", t);
        }
    }

}
